﻿namespace Creek.UI.EFML.Base.JS.ScriptingTypes
{
    using System.Collections.Generic;
    using System.Dynamic;
    using System.IO;
    using System.Text;

    using Creek.Serialize;

    public class Object : DynamicObject
    {
        public static object parse(string bin)
        {
            return new Serializer(true).Deserialize(new MemoryStream(Encoding.ASCII.GetBytes(bin)));
        }

        public static string stringify(object o)
        {
            var ms = new MemoryStream();
            new Serializer(true).Serialize(o, ms);
            return Encoding.ASCII.GetString(ms.ToArray());
        }

        #region Fields

        private readonly Dictionary<string, object> _properties = new Dictionary<string, object>();

        #endregion

        #region Constructors and Destructors

        public Object()
        {
        }

        public Object(Dictionary<string, object> props)
        {
            this._properties = props;
        }

        #endregion

        #region Public Indexers

        public object this[string k]
        {
            get
            {
                return this._properties[k];
            }
            set
            {
                this._properties[k] = value;
            }
        }

        #endregion

        #region Public Methods and Operators

        public void Add(string k, object v)
        {
            this._properties.Add(k, v);
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            return this._properties.Keys;
        }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            return this._properties.TryGetValue(binder.Name, out result);
        }

        public override bool TrySetMember(SetMemberBinder binder, object Content)
        {
            this._properties[binder.Name] = Content;
            return true;
        }

        #endregion
    }
}